"""
图片管理视图
"""
from fdfs_client.client import Fdfs_client, get_tracker_conf
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from goods.models import SKUImage, SKU
from meiduo_admin.serializers.images_serializers import *
from meiduo_admin.paginations import MyPage
from django.conf import settings

class ImagesView(ModelViewSet):
    """
    图片管理
    """
    queryset = SKUImage.objects.all()
    serializer_class = ImagesModelSerializer
    pagination_class = MyPage
    # 自定义视图函数，新建图片可选sku视图
    def simple(self, request):
        # 1.获取目标查询集
        skus = SKU.objects.all()
        # 2.获取序列化器对象
        serializer = SKUSimpleModelSerializer(instance=skus, many=True)
        # 3.构建响应
        return Response(serializer.data)
    
    # # 重写create方法，实现图片上传fdfs
    # def create(self, request, *args, **kwargs):
    #     # 获取前端传参， 前端把传来的image字段的图片数据，封装成立文件对象
    #     f = request.FILES.get('image')
    #     image_data = f.read()
    #     # 使用fdfs客户端上传图片
    #     # track_path = get_tracker_conf(settings.FDFS_PATH)
    #     conn = Fdfs_client(settings.FDFS_PATH)
    #     res = conn.upload_by_buffer(image_data)
    #     if res['Status'] !='Upload successed.':
    #         return Response({'code': 400, 'errmsg': '上传图片失败'})
    #     file_id = res['Remote file_id']
    #     # 新建SKUImage对象，保存数据库
    #     sku_id = request.POST.get('sku')
    #     image = SKUImage.objects.create(
    #         sku_id = sku_id,
    #         image = file_id # 新建模型类对象ImageField类型字段，赋值为一个字符串文件id
    #     )
    #     # 构建响应返回
    #     return Response({
    #         'id': image.id,
    #         'sku': image.sku.id,
    #         'image': image.image.url
    #     },status=201)